package com.zyp.messageboard.controller;

import com.zyp.messageboard.entity.User;
import com.zyp.messageboard.service.UserService;
import com.zyp.messageboard.service.impl.UserServiceImpl;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.security.SecureRandom;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    private final UserService userService = new UserServiceImpl();
    private static final SecureRandom random = new SecureRandom();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String rememberMe = request.getParameter("rememberMe");

        System.out.println("Received Username: " + username);
        System.out.println("Received Password: " + password);

        User user = userService.findByUsername(username);
        if (user != null && user.getPassword().equals(password)) {
            HttpSession session = request.getSession();
            session.setAttribute("user", user);

            // 更新用户在线状态
            userService.updateOnlineStatus(user.getId(), true);

            if ("on".equals(rememberMe)) {
                String token = generateToken();
                user.setRememberMeToken(token);
                userService.update(user);

                Cookie cookie = new Cookie("rememberMeToken", token);
                cookie.setMaxAge(7 * 24 * 60 * 60); // 7 days
                response.addCookie(cookie);
            }else {
                // 用户取消了“记住我”选项，删除 rememberMeToken
                user.setRememberMeToken(null);
                userService.update(user);

                Cookie cookie = new Cookie("rememberMeToken", "");
                cookie.setMaxAge(0); // 删除 cookie
                response.addCookie(cookie);
            }

            response.sendRedirect("messageList");
        } else {
            request.setAttribute("error", "Invalid username or password");
            request.getRequestDispatcher("login.jsp").forward(request, response);
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Cookie[] cookies = request.getCookies();
        String rememberMeToken = null;

        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("rememberMeToken".equals(cookie.getName())) {
                    rememberMeToken = cookie.getValue();
                    break;
                }
            }
        }

        if (rememberMeToken != null) {
            User user = userService.findByRememberMeToken(rememberMeToken);
            if (user != null) {
                // 设置用户名和密码到请求属性，以便在 JSP 中使用
                request.setAttribute("username", user.getUsername());
                request.setAttribute("password", user.getPassword()); // 注意：这里不应该存储明文密码
                request.setAttribute("rememberMe", "checked"); // 设置复选框为选中状态
            } else {
                // 如果找不到用户，清除 rememberMeToken
                Cookie cookie = new Cookie("rememberMeToken", "");
                cookie.setMaxAge(0);
                response.addCookie(cookie);
            }
        }

        request.getRequestDispatcher("login.jsp").forward(request, response);
    }

    /**
     * 生成一个随机的 Base64 编码的令牌
     *
     * @return 随机生成的令牌字符串
     */
    private String generateToken() {
        byte[] bytes = new byte[32];
        random.nextBytes(bytes);
        return java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
    }
}
